import 'package:flutter/material.dart';
import '../models/product.dart';
import '../providers/favorites_provider.dart';
import 'package:provider/provider.dart';

class ProductCard extends StatelessWidget {
  final Product product;
  final VoidCallback? onTap;
  const ProductCard({super.key, required this.product, this.onTap});

  @override
  Widget build(BuildContext context) {
    final favs = context.watch<FavoritesProvider>();
    final isFav = favs.isFav(product.id);
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      child: InkWell(
        onTap: onTap,
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Row(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Image.network(
                  product.thumbnail.isNotEmpty ? product.thumbnail : (product.images.isNotEmpty ? product.images.first : ''),
                  width: 88,
                  height: 88,
                  fit: BoxFit.cover,
                  errorBuilder: (c, e, s) => Container(
                    width: 88,
                    height: 88,
                    color: Colors.grey.shade300,
                    child: const Icon(Icons.broken_image),
                  ),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(product.title, maxLines: 2, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.titleMedium),
                    const SizedBox(height: 6),
                    Text(product.description, maxLines: 2, overflow: TextOverflow.ellipsis),
                    const SizedBox(height: 6),
                    Wrap(spacing: 6, runSpacing: -8, children: [
                      Chip(label: Text(product.category), visualDensity: VisualDensity.compact),
                      if (product.brand.isNotEmpty) Chip(label: Text(product.brand), visualDensity: VisualDensity.compact),
                    ]),
                  ],
                ),
              ),
              const SizedBox(width: 8),
              AnimatedScale(
                scale: isFav ? 1.2 : 1.0,
                duration: const Duration(milliseconds: 240),
                child: IconButton(
                  icon: Icon(isFav ? Icons.favorite : Icons.favorite_border, color: isFav ? Colors.red : null),
                  onPressed: () => favs.toggle(product),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}